package cn.maihe.elg.operation.centers.follow.handler.service;

import cn.maihe.elg.operation.centers.follow.enums.BeianDiquCode;
import cn.maihe.elg.operation.centers.follow.handler.FollowCenterTradeService;
import cn.maihe.elg.operation.centers.follow.handler.dto.ApplyGuaranteeReqDTO;
import cn.maihe.elg.operation.centers.follow.handler.dto.ApplyGuaranteeRespDTO;
import cn.maihe.elg.operation.centers.follow.handler.dto.bo.ApplicantBO;
import cn.maihe.elg.operation.centers.follow.handler.dto.bo.AssuredBO;
import cn.maihe.elg.operation.centers.follow.handler.dto.bo.ProjectBO;
import cn.maihe.elg.operation.centers.follow.handler.dto.bo.UserBO;
import cn.maihe.elg.operation.centers.hymake.dto.handler.FilePushReqDTO;
import cn.maihe.elg.operation.centers.hymake.handler.service.HyMakeFilePushService;
import cn.maihe.elg.operation.centers.supports.CenterTradeContext;
import cn.maihe.elg.operation.centers.supports.annotation.CenterTradeService;
import cn.maihe.elg.operation.common.Constants;
import cn.maihe.elg.operation.config.ImageUploadConfig;
import cn.maihe.elg.operation.model.bo.AcceptOrderBO;
import cn.maihe.elg.operation.model.bo.ApplyTemplatePdfParams;
import cn.maihe.elg.operation.model.enums.*;
import cn.maihe.elg.operation.repository.entity.*;
import cn.maihe.elg.operation.service.business.CustomerAttachmentService;
import cn.maihe.elg.operation.service.order.AcceptOrderInfoService;
import cn.maihe.elg.operation.service.order.GuaranteeAttachmentInfoService;
import cn.maihe.elg.operation.supports.system.ElgResourceService;
import cn.maihe.elg.operation.utils.DateUtil;
import cn.maihe.elg.operation.utils.ElgLogger;
import cn.maihe.elg.operation.utils.IdGenerate;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Triple;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @Description
 * @Author caixh
 * @Date 2021/9/17.
 */
@CenterTradeService(
        provider = CenterProviderEnum.FOLLOW,
        centerNo = CenterNoEnum.SANMING,
        tradeType = TradeType.apply_guarantee,
        reqClass = ApplyGuaranteeReqDTO.class,
        respClass = ApplyGuaranteeRespDTO.class
)
@Slf4j
public class FollowApplyGuaranteeService extends FollowCenterTradeService<ApplyGuaranteeReqDTO, ApplyGuaranteeRespDTO> {

    @Resource
    private AcceptOrderInfoService acceptOrderInfoService;
    @Resource
    private ElgResourceService elgResourceService;
    @Value("${homeBaseUrl}")
    private String homeBaseUrl;
    @Resource
    private GuaranteeAttachmentInfoService guaranteeAttachmentInfoService;
    @Resource
    private CustomerAttachmentService customerAttachmentService;
    @Resource
    private ImageUploadConfig imageUploadConfig;

    /**
     * 具体业务处理
     *
     * @param context
     */
    @Override
    public ApplyGuaranteeRespDTO processService(CenterTradeContext<ApplyGuaranteeReqDTO, ApplyGuaranteeRespDTO> context) {

        AcceptOrderBO acceptOrderBO = this.parseApplyGuaranteeInfo(context);

        acceptOrderBO = acceptOrderInfoService.saveAcceptOrderBO(acceptOrderBO);

        AcceptOrderInfoDO acceptOrderInfoDO = acceptOrderBO.getAcceptOrderInfo();
        acceptOrderBO.getFileInfos().stream().forEach(fileInfo -> {
            try {
                this.downloadFile(acceptOrderInfoDO, fileInfo);
            } catch (Exception e) {
                log.error("下载保存推送材料失败：{}", e.getMessage(), e);
                throw new RuntimeException("下载保存推送材料失败：" + e.getMessage(), e);
            }
        });
        ApplyGuaranteeRespDTO resp = buildResp(acceptOrderBO);
        return resp;

    }

    private ApplyGuaranteeRespDTO buildResp(AcceptOrderBO acceptOrderBO) {
        ApplyGuaranteeRespDTO applyGuaranteeRespDTO = new ApplyGuaranteeRespDTO();
        applyGuaranteeRespDTO.setOrder_sn(acceptOrderBO.getAcceptOrderInfo().getAcceptOrderNo());
        if (acceptOrderBO.getCenterNo() == CenterNoEnum.YOUXI) {
            applyGuaranteeRespDTO.setMin_premium("50.00");
        } else if (acceptOrderBO.getCenterNo() == CenterNoEnum.JIANGLE) {
            applyGuaranteeRespDTO.setMin_premium("100.00");
        } else {
            applyGuaranteeRespDTO.setMin_premium("300.00");
            applyGuaranteeRespDTO.setRate("0.0015");
        }
//        String url = homeBaseUrl + "/#/autoLogin?mobile=" + acceptOrderBO.getBidCustomer().getBidderCreditCode() + "&ordersn=" + acceptOrderBO.getAcceptOrderInfo().getAcceptOrderNo();
//        applyGuaranteeRespDTO.setUrl(url);

        //投标企业是否已提交企业认证资料且已审核通过
        BidCustomerDO bidCustomerDO = acceptOrderBO.getBidCustomer();
        if (BidCustomerStatus.NORMAL.getStatus() != bidCustomerDO.getStatus()) {
            //非正常状态跳转到投标人认证资料补充页面
            applyGuaranteeRespDTO.setUrl(elgResourceService.buildElgFrontUrl("/#/autoLogin?mobile=" + acceptOrderBO.getUserDO().getUsername() + "&ordersn=" + acceptOrderBO.getAcceptOrderInfo().getAcceptOrderNo()));
        } else {
            //跳转到该订单上传申请书&反担保协议书 及 支付凭证页面
            applyGuaranteeRespDTO.setUrl(elgResourceService.buildElgFrontUrl("/#/autoLogin?mobile=" + acceptOrderBO.getUserDO().getUsername() + "&ordersn=" + acceptOrderBO.getAcceptOrderInfo().getAcceptOrderNo()));
        }
//        if (BidCustomerStatus.NORMAL.getStatus() == bidCustomerDO.getStatus()) {
//            //跳转到该订单上传申请书&反担保协议书 及 支付凭证页面
        makeAndSaveApplyFile(acceptOrderBO);
//        }

        return applyGuaranteeRespDTO;
    }

    /**
     * docx模板合成申请书
     */
    private void makeAndSaveApplyFile(AcceptOrderBO acceptOrderBO) {
        ApplyTemplatePdfParams params = new ApplyTemplatePdfParams();
        params.setBidderName(acceptOrderBO.getBidCustomer().getBidderName());
        params.setProjectName(acceptOrderBO.getProjectInfo().getProjectName());
        Triple<String, String, String> triple = DateUtil.parseLocalDate();
        params.setYear(triple.getLeft());
        params.setMonth(triple.getMiddle());
        params.setDay(triple.getRight());
        AcceptOrderInfoDO orderInfo = acceptOrderBO.getAcceptOrderInfo();
        String acceptOrderNo = orderInfo.getAcceptOrderNo();
        Path pdfPath = elgResourceService.buildApplyFileByTemplate(acceptOrderNo, params);

        guaranteeAttachmentInfoService.saveOrUpdateAttachmentInfo(orderInfo, pdfPath, AttachmentFileType.TYPE_12, "申请书未签章");

    }


    private AcceptOrderBO parseApplyGuaranteeInfo(CenterTradeContext<ApplyGuaranteeReqDTO, ApplyGuaranteeRespDTO> context) {
        ApplyGuaranteeReqDTO req = context.getReq();
//        long centerId = context.getCenterId();
        long orgId = context.getOrgId();

        BeianDiquCode beianDiqu = BeianDiquCode.resolve(req.getData().getUser().getBeiandiqu_code());
        long centerId = getCurCenterId(beianDiqu.getCenterNo());
        context.setCenterId(beianDiqu.getCenterNo().getCenterNo(), centerId);
//        centerId = beianDiqu.getCenterNo().get

        //FIXME 目前提供 得兴担保直开式 无法获取出函机构，目前暂内置指定得兴的出函机构，后续有多个需上游接口支持或者内部选择
        InstitutionOrgCodeEnum institutionOrgCodeEnum = InstitutionOrgCodeEnum.resolve(context.getOrgCode());
//        InstitutionCode curInstitutionCode = InstitutionCode.deXing;
        GuaranteeInstitutionDO institutionDO = getInstitutionIdByCode(institutionOrgCodeEnum);
        ProjectInfoDO projectInfoDO = this.buildProjectInfo(req, centerId, orgId);
        BidCustomerDO bidCustomerDO = this.buildBidCustomerInfo(req, centerId, orgId);
        UserDO userDO = this.buildUserInfo(req, centerId, orgId);
//        List<CustomerAttachmentDO> customerAttachmentDOS = this.buildCustomerAttachmentList(req, bidCustomerDO.getFollowId());

        AcceptOrderInfoDO acceptOrderInfoDO = this.buildAcceptOrderInfo(req, centerId, orgId, institutionDO, context.getCenterNo());
        String acceptOrderNo = acceptOrderInfoDO.getAcceptOrderNo();
//        List<GuaranteeAttachmentInfoDO> attachmentInfoDOList = this.buildGuaranteeAttachmentInfo(req, centerId, orgId, acceptOrderNo);

        List<FilePushReqDTO.FileInfo> fileInfos = new ArrayList<>();
        if (req.getData().getApplicant().getLicense_files() != null) {
            FilePushReqDTO.FileInfo lFileInfo = new FilePushReqDTO.FileInfo();
            lFileInfo.setUrl(req.getData().getApplicant().getLicense_files().get(0));
            lFileInfo.setFileTypeName(HyMakeFilePushService.FileTypeNameEnum.TYPE03.getFileTypeName());
            fileInfos.add(lFileInfo);
        }
        if (req.getData().getApplicant().getQualification_files() != null) {
            FilePushReqDTO.FileInfo qFileInfo = new FilePushReqDTO.FileInfo();
            qFileInfo.setUrl(req.getData().getApplicant().getQualification_files().get(0));
            qFileInfo.setFileTypeName(HyMakeFilePushService.FileTypeNameEnum.TYPE04.getFileTypeName());
            fileInfos.add(qFileInfo);
        }


        acceptOrderInfoDO.setFeeRate(new BigDecimal(0.0015).multiply(new BigDecimal("100")).setScale(4, RoundingMode.HALF_UP).toString());
        if (beianDiqu.getCenterNo() == CenterNoEnum.YOUXI) {
            acceptOrderInfoDO.setGuaranteeFee(getYouxiGuaranteeFee(projectInfoDO.getContractReckonPrice()));
        } else if (beianDiqu.getCenterNo() == CenterNoEnum.JIANGLE) {
            acceptOrderInfoDO.setGuaranteeFee(getJiangLeGuaranteeFee(projectInfoDO.getBidBond()));
        }


        AcceptOrderBO orderBO = AcceptOrderBO.builder().centerId(centerId).orgId(orgId).fileInfos(fileInfos)
//                .attachmentInfoDOList(attachmentInfoDOList)
                .acceptOrderInfo(acceptOrderInfoDO).projectInfo(projectInfoDO).bidCustomer(bidCustomerDO).userDO(userDO).centerNo(beianDiqu.getCenterNo()).build();

        //默认投标保函类别;FIXME 后续按实际入参提取
        orderBO.setGuaranteeCategory(GuaranteeCategory.BID);
        //默认担保公司担保类型;FIXME 后续按实际入参提取
        orderBO.setGuaranteeType(GuaranteeType.GUARANTEE);


        orderBO.setInstitutionOrgCodeEnum(institutionOrgCodeEnum);
        orderBO.setIsInnerApply(true);

        //出函机构赋值
        acceptOrderInfoDO.setInstitutionId(institutionDO.getId());
        acceptOrderInfoDO.setGuaranteeType(orderBO.getGuaranteeType().getTypeStr());
        acceptOrderInfoDO.setGuaranteeCategory(orderBO.getGuaranteeCategory().getCategoryStr());

        return orderBO;

    }

    private void downloadFile(AcceptOrderInfoDO acceptOrderInfo, FilePushReqDTO.FileInfo fileInfo) throws Exception {
        String fileTypeName = fileInfo.getFileTypeName();
        AttachmentFileType attachmentFileType = HyMakeFilePushService.FileTypeNameEnum.toGuaranteeAttachmentFileType(fileTypeName);
        CustomerAttachmentTypeEnum customerAttachmentTypeEnum = HyMakeFilePushService.FileTypeNameEnum.toCustomerAttachmentFileType(fileTypeName);
        if (attachmentFileType != null) {
            this.saveOrUpdateGuaranteeAttachInfo(attachmentFileType, acceptOrderInfo, fileInfo);
        } else if (customerAttachmentTypeEnum != null) {
            this.saveOrUpdateCustomerAttachInfo(customerAttachmentTypeEnum, acceptOrderInfo, fileInfo);
        }

    }

    private void saveOrUpdateCustomerAttachInfo(CustomerAttachmentTypeEnum customerAttachmentType, AcceptOrderInfoDO acceptOrderInfo, FilePushReqDTO.FileInfo fileInfo) throws Exception {
        String fileUrl = fileInfo.getUrl();
        String md5Value = fileInfo.getMd5Value();
        Long bidCustomerId = acceptOrderInfo.getBidCustomerId();
        CustomerAttachmentDO customerAttachment = customerAttachmentService.getCustomerAttachment(bidCustomerId, customerAttachmentType);
        if (customerAttachment != null) {
            md5Value = customerAttachment.getFileMd5();
        }
        if (customerAttachment == null) {
            Path tmpPath = elgResourceService.downloadByURL(fileUrl);
//            String relativePath = elgResourceService.transferAndSaveFile(tmpPath, "ofd", bidCustomerId.toString(), fileInfo.getFileTypeName());
            String relativePath = UUID.randomUUID().toString() + "." + elgResourceService.getFileType(tmpPath);
            md5Value = elgResourceService.getFileMD5AsHex(tmpPath);
            Path registerDir = Paths.get(imageUploadConfig.getPath(), Constants.REGIST_IMAGE_PATH);
            if (Files.notExists(registerDir)) {
                Files.createDirectories(registerDir);
            }
            Path registerImg = registerDir.resolve(relativePath);
            Files.copy(tmpPath, registerImg, StandardCopyOption.REPLACE_EXISTING);

            Files.deleteIfExists(tmpPath);

            customerAttachment = new CustomerAttachmentDO();
            customerAttachment.setId(IdGenerate.getId());
            customerAttachment.setBidderId(bidCustomerId);
            customerAttachment.setAttachType(customerAttachmentType.getType());
            customerAttachment.setAttachPath(relativePath);
            customerAttachment.setAttachFileName(relativePath);
            customerAttachment.setFileMd5(md5Value);
            customerAttachment.setFileUrl(fileUrl);

            customerAttachmentService.insert(customerAttachment);
        } else if (md5Value == null || !md5Value.equalsIgnoreCase(customerAttachment.getFileMd5())) {
            Path tmpPath = elgResourceService.downloadByURL(fileUrl);
//            String relativePath = elgResourceService.transferAndSaveFile(tmpPath, "ofd", bidCustomerId.toString(), fileInfo.getFileTypeName());
            String relativePath = UUID.randomUUID().toString() + "." + elgResourceService.getFileType(tmpPath);
            md5Value = elgResourceService.getFileMD5AsHex(tmpPath);
            Path registerDir = Paths.get(imageUploadConfig.getPath(), Constants.REGIST_IMAGE_PATH);
            if (Files.notExists(registerDir)) {
                Files.createDirectories(registerDir);
            }
            Path registerImg = registerDir.resolve(relativePath);
            Files.copy(tmpPath, registerImg, StandardCopyOption.REPLACE_EXISTING);

            Files.deleteIfExists(tmpPath);


            customerAttachment.setBidderId(bidCustomerId);
            customerAttachment.setAttachType(customerAttachmentType.getType());
            customerAttachment.setAttachPath(relativePath);
            customerAttachment.setAttachFileName(relativePath);
            customerAttachment.setFileMd5(md5Value);
            customerAttachment.setFileUrl(fileUrl);

            customerAttachmentService.updateById(customerAttachment);
        }

    }

    private void saveOrUpdateGuaranteeAttachInfo(AttachmentFileType attachmentFileType, AcceptOrderInfoDO acceptOrderInfo, FilePushReqDTO.FileInfo fileInfo) throws Exception {
        String fileUrl = fileInfo.getUrl();
        String md5Value = fileInfo.getMd5Value();
        String acceptOrderNo = acceptOrderInfo.getAcceptOrderNo();
        GuaranteeAttachmentInfoDO guaranteeAttachmentInfo = guaranteeAttachmentInfoService.getTypeAttachmentByAcceptOrderNo(acceptOrderNo, attachmentFileType);
        if (guaranteeAttachmentInfo != null) {
            md5Value = guaranteeAttachmentInfo.getFileMd5();
        }
        if (guaranteeAttachmentInfo == null) {
            Path tmpPath = elgResourceService.downloadByURL(fileUrl);
            String relativePath = elgResourceService.transferAndSaveFile(tmpPath, "ofd", acceptOrderNo, fileInfo.getFileTypeName());
            md5Value = elgResourceService.getFileMD5AsHex(elgResourceService.getAbsolutePath(relativePath));
            Files.deleteIfExists(tmpPath);

            guaranteeAttachmentInfo = new GuaranteeAttachmentInfoDO();
            guaranteeAttachmentInfo.setId(IdGenerate.getId());
            guaranteeAttachmentInfo.setCenterId(acceptOrderInfo.getCenterId());
            guaranteeAttachmentInfo.setOrgId(acceptOrderInfo.getOrgId());
            guaranteeAttachmentInfo.setAcceptOrderNo(acceptOrderInfo.getAcceptOrderNo());
            guaranteeAttachmentInfo.setType(attachmentFileType.getType());
            guaranteeAttachmentInfo.setFileName(fileInfo.getFileTypeName());
            guaranteeAttachmentInfo.setFileType(fileInfo.getFileType());
            guaranteeAttachmentInfo.setFileMd5(md5Value);
            guaranteeAttachmentInfo.setFilePath(relativePath);
            guaranteeAttachmentInfo.setRemark("新增" + attachmentFileType.getDesc());
            guaranteeAttachmentInfo.setFileUrl(fileInfo.getUrl());

            guaranteeAttachmentInfoService.insert(guaranteeAttachmentInfo);
        } else if (md5Value == null || !md5Value.equalsIgnoreCase(guaranteeAttachmentInfo.getFileMd5())) {
            Path tmpPath = elgResourceService.downloadByURL(fileUrl);
            String relativePath = elgResourceService.transferAndSaveFile(tmpPath, "ofd", acceptOrderNo, fileInfo.getFileTypeName());
            md5Value = elgResourceService.getFileMD5AsHex(elgResourceService.getAbsolutePath(relativePath));
            Files.deleteIfExists(tmpPath);

            guaranteeAttachmentInfo.setCenterId(acceptOrderInfo.getCenterId());
            guaranteeAttachmentInfo.setOrgId(acceptOrderInfo.getOrgId());
            guaranteeAttachmentInfo.setAcceptOrderNo(acceptOrderInfo.getAcceptOrderNo());
            guaranteeAttachmentInfo.setType(attachmentFileType.getType());
            guaranteeAttachmentInfo.setFileName(fileInfo.getFileTypeName());
            guaranteeAttachmentInfo.setFileType(fileInfo.getFileType());
            guaranteeAttachmentInfo.setFileMd5(md5Value);
            guaranteeAttachmentInfo.setFilePath(relativePath);
            guaranteeAttachmentInfo.setRemark("更新" + attachmentFileType.getDesc());
            guaranteeAttachmentInfo.setFileUrl(fileInfo.getUrl());

            guaranteeAttachmentInfoService.updateById(guaranteeAttachmentInfo);
        }

    }

    private List<CustomerAttachmentDO> buildCustomerAttachmentList(ApplyGuaranteeReqDTO req, String followId) {
        List<CustomerAttachmentDO> retList = req.getData().getApplicant().getLicense_files()
                .stream().parallel().map(fileUrl -> {

                    CustomerAttachmentDO customerAttachmentDO = new CustomerAttachmentDO();
                    try {
                        Path tmpPath = elgResourceService.downloadByURL(fileUrl);
//                        String fileType = elgResourceService.getFileType(tmpPath);
                        String relativePath = elgResourceService.save2OfdPath(tmpPath, followId, IdGenerate.getIdStr());
                        String fileMd5 = elgResourceService.getFileMD5AsHex(elgResourceService.getAbsolutePath(relativePath));

                        customerAttachmentDO.setFileUrl(fileUrl);
                        customerAttachmentDO.setFileMd5(fileMd5);
                        customerAttachmentDO.setAttachPath(relativePath);
                        customerAttachmentDO.setAttachType(CustomerAttachmentTypeEnum.TYPE_0.getType());
                    } catch (Exception e) {
//                        cur.setRemark(e.getMessage());
                        ElgLogger.error(log, log -> log.error("构造签署文件对象异常:{}", e.getMessage(), e));
                    }
                    return customerAttachmentDO;
                }).collect(Collectors.toList());

        return retList;
    }

    private List<GuaranteeAttachmentInfoDO> buildGuaranteeAttachmentInfo(ApplyGuaranteeReqDTO req, long centerId, long orgId, String acceptOrderNo) {
        List<GuaranteeAttachmentInfoDO> reList = Lists.newArrayList();

        List<GuaranteeAttachmentInfoDO> lFileList = req.getData().getApplicant().getLicense_files()
                .stream().parallel().map(fileUrl -> {
                    GuaranteeAttachmentInfoDO cur = new GuaranteeAttachmentInfoDO();
                    cur.setId(IdGenerate.getId());
                    cur.setOrgId(orgId);
                    cur.setCenterId(centerId);
                    cur.setAcceptOrderNo(acceptOrderNo);
//                    cur.setFileName(l.getFile_name());
//                    cur.setFileId(l.getFile_id());
                    cur.setFileUrl(fileUrl);
//                    int type = getAttachmentFileTypeByFileName(l.getFile_name()).getType();
                    cur.setType(AttachmentFileType.TYPE_3.getType());
                    try {
                        Path tmpPath = elgResourceService.downloadByURL(fileUrl);
                        String fileType = elgResourceService.getFileType(tmpPath);
                        String relativePath = elgResourceService.save2OfdPath(tmpPath, acceptOrderNo, IdGenerate.getIdStr());
                        String fileMd5 = elgResourceService.getFileMD5AsHex(elgResourceService.getAbsolutePath(relativePath));

                        cur.setFilePath(relativePath);
                        cur.setFileType(fileType);
                        cur.setFileMd5(fileMd5);
                    } catch (Exception e) {
                        cur.setRemark(e.getMessage());
                        ElgLogger.error(log, log -> log.error("构造签署文件对象异常:{}", e.getMessage(), e));
                    }
                    return cur;
                }).collect(Collectors.toList());
        if (lFileList != null) {
            reList.addAll(lFileList);
        }
        List<GuaranteeAttachmentInfoDO> qFileList = req.getData().getApplicant().getQualification_files()
                .stream().parallel().map(fileUrl -> {
                    GuaranteeAttachmentInfoDO cur = new GuaranteeAttachmentInfoDO();
                    cur.setId(IdGenerate.getId());
                    cur.setOrgId(orgId);
                    cur.setCenterId(centerId);
                    cur.setAcceptOrderNo(acceptOrderNo);
//                    cur.setFileName(l.getFile_name());
//                    cur.setFileId(l.getFile_id());
                    cur.setFileUrl(fileUrl);
//                    int type = getAttachmentFileTypeByFileName(l.getFile_name()).getType();
                    cur.setType(AttachmentFileType.TYPE_2.getType());
                    try {
                        Path tmpPath = elgResourceService.downloadByURL(fileUrl);
                        String fileType = elgResourceService.getFileType(tmpPath);
                        String relativePath = elgResourceService.save2OfdPath(tmpPath, acceptOrderNo, IdGenerate.getIdStr());
                        String fileMd5 = elgResourceService.getFileMD5AsHex(elgResourceService.getAbsolutePath(relativePath));

                        cur.setFilePath(relativePath);
                        cur.setFileType(fileType);
                        cur.setFileMd5(fileMd5);
                    } catch (Exception e) {
                        cur.setRemark(e.getMessage());
                        ElgLogger.error(log, log -> log.error("构造签署文件对象异常:{}", e.getMessage(), e));
                    }
                    return cur;
                }).collect(Collectors.toList());

        if (qFileList != null) {
            reList.addAll(qFileList);
        }
        return reList;
    }

    private AcceptOrderInfoDO buildAcceptOrderInfo(ApplyGuaranteeReqDTO req, long centerId, long orgId, GuaranteeInstitutionDO institutionDO, String centerNo) {
        ProjectBO projectBO = req.getData().getProject();
        return AcceptOrderInfoDO.builder()
                .centerId(centerId)
                .orgId(orgId)
                .guaranteeNo(IdGenerate.genGuaranteeNo(institutionDO.getInstitutionCode()))

                .centerOrderId(req.getRequestid())
                .certifyCode(req.getData().getUser().getBeiandiqu_code())
                .centerOrderTime(DateUtil.getDatetime())
                .acceptOrderNo(IdGenerate.genAcceptOrderNo(CenterNoEnum.resolve(centerNo)))
                .projectName(projectBO.getName())
                .sectionName(projectBO.getBd_name())
                .bidCustomerName(req.getData().getApplicant().getApplicant_name())
//                .bidIndate()
                .guaranteeType(null)//'保函类型'
                .guaranteeCategory(null) //'保函品种'
                .templateId(null)//'报价模板主键id'
                .bidIndate(DateUtil.getDateFromString(projectBO.getBzj_etime(), DateUtil.FORMAT_DATETIME))
                .guaranteeFee(getGuaranteeFee(yuan2fenLong(projectBO.getAmount())))//'保费金额分'
                .status(AcceptOrderStatus.WAIT_FIRST_TRAIL.getStatus())
                .guaranteeTime(null)
                .projectId(null)//  '投保项目主键id' 关联保存时统一设置
                .bidCustomerId(null)// '投保客户主键id'
                .institutionId(null) //???'开函机构主键' 怎么关联上
                .attachmentId(null)// ??? TODO 解析附件内容，接口获取文件并转换系统存储Id
                .applyOrderNo(null)
                .invoiceFlag(null)
                .invoiceId(null)
                .warnFlag(0).warnContent(null)
                .gmtCreate(Date.from(Instant.now()))
                .build();
    }

    private Long getYouxiGuaranteeFee(Long projectAmount) {
        if (projectAmount <= 50000000L) {
            return 5000L;
        } else if (projectAmount <= 100000000L) {
            return 10000L;
        } else if (projectAmount <= 200000000L) {
            return 15000L;
        } else if (projectAmount <= 400000000L) {
            return 20000L;
        }
        return 20000L;
    }

    private Long getJiangLeGuaranteeFee(Long projectAmount) {
        if (projectAmount < 2000000L) {
            return 10000L;
        } else if (projectAmount < 4000000L) {
            return 15000L;
        } else if (projectAmount < 8000000L) {
            return 20000L;
        } else if (projectAmount <= 20000000L) {
            return 30000L;
        } else {
            return Math.round(projectAmount * 0.0015);
        }
    }

    private Long getGuaranteeFee(Long bidBond) {
        Long guaranteeFee = 0L;
        if (bidBond != null) {
            guaranteeFee = new BigDecimal(bidBond).multiply(new BigDecimal("0.0015")).longValue();
            guaranteeFee = guaranteeFee < 30000 ? 30000 : guaranteeFee;
        }
        return guaranteeFee;
    }

    private UserDO buildUserInfo(ApplyGuaranteeReqDTO req, long centerId, long orgId) {
        UserBO userBO = req.getData().getUser();
        ApplicantBO applicantBO = req.getData().getApplicant();
        return UserDO.builder()
                .umLogin("0")
                .followId(userBO.getUserid())
                .username(applicantBO.getCredit_code())
                .mobileNo(userBO.getMobile())
                .name(userBO.getUsername())
                .type(UserType.BIDDER.getType())
                .status(UserStatusEnum.NORMAL.name())
                .orgCode("-1")
                .gmtCreate(new Date())
                .gmtModified(new Date())
                .build();
    }

    private BidCustomerDO buildBidCustomerInfo(ApplyGuaranteeReqDTO req, long centerId, long orgId) {
        UserBO userBO = req.getData().getUser();
        ApplicantBO applicantBO = req.getData().getApplicant();
        return BidCustomerDO.builder()
                .centerId(centerId)
                .orgId(orgId)
                .bidderName(applicantBO.getApplicant_name())
                .bidderCreditCode(applicantBO.getCredit_code())

                .comTelArea(applicantBO.getCom_tel_area())
                .comTelNum(applicantBO.getCom_tel_num())
                .province(applicantBO.getProvince())
                .city(applicantBO.getCity())
                .district(applicantBO.getDistrict())
                .bidderEndDate(applicantBO.getCredit_vld())
                .bidderContactName(applicantBO.getContact_name())
                .bidderContactTel(applicantBO.getContact_mobile())
                .bidderContactIdcard(applicantBO.getContact_idcard())
                .bidderContactIdcardType(IDType.ID_CARD.getType())
                .bidderAddress(applicantBO.getAddress())
                .bidderRegAddress(applicantBO.getAddress())
                .bidderEamil(applicantBO.getEmail())
                .bidderLegal(applicantBO.getLegal_name())
                .legalPersonName(applicantBO.getLegal_name())
                .legalPersonIdcard(applicantBO.getLegal_num())
                .legalPersonTel(applicantBO.getCom_tel_num())
                .legalPersonIdcardType(IDType.ID_CARD.getType())

                .licenseLegal(applicantBO.getLegal_name())
                .followId(userBO.getUnitid())
                .beiandiquCode(userBO.getBeiandiqu_code())
                .bankName(userBO.getBank_name())
                .bankCardNum(userBO.getBank_card_num())
                .bankUserName(userBO.getBank_user_name())

                .gmtCreate(Date.from(Instant.now()))
                .build();
    }

    private ProjectInfoDO buildProjectInfo(ApplyGuaranteeReqDTO req, long centerId, long orgId) {
        ProjectBO projectBO = req.getData().getProject();
        AssuredBO assuredBO = req.getData().getAssured();

        if (StringUtils.isEmpty(projectBO.getBdid())) {
            projectBO.setBdid(projectBO.getTpid());
        }
        if (StringUtils.isEmpty(projectBO.getBd_name())) {
            projectBO.setBd_name(projectBO.getName());
        }

        return ProjectInfoDO.builder()
                .centerId(centerId)
                .orgId(orgId)
                .projectName(projectBO.getName())
                .projectCode(projectBO.getTpid())
                .sectionCode(projectBO.getBdid())
                .sectionName(projectBO.getBd_name())

                .bidOpenTime(DateUtil.getDateFromString(projectBO.getStart_date(), DateUtil.FORMAT_DATETIME))
                .bidBond(yuan2fenLong(projectBO.getAmount()))

                .cityCode(projectBO.getProvince().concat(",")
                        .concat(projectBO.getCity()).concat(",")
                        .concat(projectBO.getDistrict())
                )
                //todo bzj_time createtime plan_date bulid_place
                .contractReckonPrice(StringUtils.isNoneEmpty(projectBO.getBulid_price()) ? yuan2fenLong(projectBO.getBulid_price()) : 0L)
                .tenderProjectType(projectBO.getTender_project_type())
                .tenderNoticeUrl(projectBO.getTender_notice_url())
                .tenderFileUrl(projectBO.getTender_file_url())
                .tenderFileMd5(projectBO.getTender_file_url_md5())
                .tendererDate(DateUtil.getDateFromString(projectBO.getCreatetime(), DateUtil.FORMAT_DATETIME))

                .tenderer(assuredBO.getAssured_name())
//                .tendererContactTel(assuredBO.getCom_tel_num())
                //todo com_tel_area credit_vld 地址
                .tendererCreditCode(assuredBO.getCredit_code())
                .tendererContact(assuredBO.getContact_name())
                .tendererContactTel(assuredBO.getContact_mobile())
                .tendererAddress(assuredBO.getAddress())
                .tendererBankOpenbank(assuredBO.getTender_bank_openbank())
                .tendererBankAccount(assuredBO.getTender_account_name())
                .tendererBankCode(assuredBO.getTender_bank_account())
                .bidIndate(DateUtil.getDateFromString(projectBO.getBzj_etime(), DateUtil.FORMAT_DATETIME))
                .validPeriod(validPeriod(projectBO.getValid_period()))
                .noticePubDate(StringUtils.isNotBlank(projectBO.getCreatetime()) ? DateUtil.parseDate(projectBO.getCreatetime(), "yyyy-MM-dd HH:mm:ss") : null)
                .warnFlag(0)
                .sourceFlag(0)
//                .gmtCreate(Date.from(Instant.now()))
                .build();
    }

    private Integer validPeriod(String validPeriod) {
        if (StringUtils.isEmpty(validPeriod) || validPeriod.equals("-")) {
            return 60;
        }
        return Integer.parseInt(validPeriod.replace("天", ""));
    }

    private Long buildPrice2Number(String buildPrice) {
        if (StringUtils.isNotEmpty(buildPrice) && !buildPrice.equals("-")) {
            try {
                return yuan2fenLong(buildPrice);
            } catch (Exception e) {
                log.error("金额转换失败：{}", e.getMessage(), e);
            }
        }

        return 0L;
    }
}
